package com.amos.mqserver.util;

import org.springframework.util.StringUtils;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

/**
 * 日期操作类
 * @author zhuqb
 *
 */
public class DateUtil {
    private static final ThreadLocal<SimpleDateFormat> local = new ThreadLocal();
    private static final String formatStr = "yyyy-MM-dd";

    public DateUtil() {
    }

    public static String formatDate(Date date) {
        return getDataFormat().format(date);
    }

    public static Date parseDate(String dataStr) {
        if (!StringUtils.isEmpty(dataStr)) {
            try {
                return getDataFormat().parse(dataStr);
            } catch (Exception var2) {
                return new Date();
            }
        } else {
            return null;
        }
    }

    private static SimpleDateFormat getDataFormat() {
        SimpleDateFormat sdf = (SimpleDateFormat)local.get();
        if (sdf == null) {
            sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            local.set(sdf);
        }

        return sdf;
    }

    public static Date addDateByHour(Date date, int hour) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(10, hour);
        return calendar.getTime();
    }

    public static Date parseFormatDate(String dataStr, String format) {
        if (!StringUtils.isEmpty(dataStr)) {
            try {
                return (new SimpleDateFormat(format)).parse(dataStr);
            } catch (Exception var3) {
                return null;
            }
        } else {
            return null;
        }
    }

    public static Date parseFormatDate(String dataStr) {
        return parseFormatDate(dataStr, "yyyy-MM-dd");
    }

    public static String parseFormatDate(Date date, String format) {
        if (date != null) {
            try {
                return (new SimpleDateFormat(format)).format(date);
            } catch (Exception var3) {
                return null;
            }
        } else {
            return null;
        }
    }

    public static String parseFormatDate(Date date) {
        return parseFormatDate(date, "yyyy-MM-dd");
    }

    public static String transferDate(Long time, String pattern) {
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        Date date = new Date(time);
        return sdf.format(date);
    }

    public static final Date getBeforDate(int day) {
        Date now = new Date();
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(now);
        calendar.add(13, -day * 24 * 3600);
        return calendar.getTime();
    }
}
